<template>
  <div class="timing">
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline queryFrom">
          <el-form-item label="任务名称">
            <el-input v-model="formInline.dataModelName" clearable placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item>
            <el-button plain @click="getUserList"><Icon type="ios-search" />查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-button type="primary" @click="addUser('add')"><Icon type="md-add" />创建HTTP接入</el-button>
        <el-button @click="testFun">测 试</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <ykhttb
      ref="httbRef"
      width="250" 
      :btn-is-show="btnIsShow"
      :table-col="tabUserList"
      :table-data="tableUserData"
      @getDataDetileInfo="getDataDetileInfo"
      @deleteSelectData="deleteSelectData"
      @refresh="getUserList"
    >
  </ykhttb>
    <!-- 分页 -->
    <div style="text-align:right;margin-top:10px;">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :close-on-click-modal="false" :title="title" :width="width" :visible.sync="dialogTableVisible">
      <!-- 名称和路径必输 -->
      <el-form v-if="dialogTableVisible" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" class="demo-ruleForm autoClass">
        <el-form-item label="接入名称" prop="joinName">
          <el-input v-model="ruleForm['joinName']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="API接口地址" prop="apiAddress">
          <el-input v-model="ruleForm['apiAddress']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="请求类型" prop="requestType">
          <el-select v-model="ruleForm['requestType']">
            <el-option value="GET" label="GET"></el-option>
            <el-option value="POST" label="POST"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="AppId" prop="appId">
          <el-input v-model="ruleForm['appId']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="AppKey" prop="appKey">
          <el-input v-model="ruleForm['appKey']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
      
        <el-form-item label="指定结构" prop="structure">
          <el-input v-model="ruleForm['structure']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-input v-model="ruleForm['tableName']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cron">
          <!-- @focus="innerVisible=true" -->
          <el-select v-model="ruleForm['cron']">
            <el-option v-for="(item,index) in cronList" :key="index" :value="item.cron" :label="item.dispatchName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型" prop="modelId">
          <el-select @change="setdataModelTypeName(ruleForm['modelId'])" v-model="ruleForm['modelId']">
            <el-option v-for="(item,index) in moduleListOptions" :key="index" :value="item.id" :label="item.dataModelName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm['requestType']=='POST'" label="Body参数" prop="bodyData" style="width: 100%;">
          <vueJsonEditor :disabled="disFlag" @has-error="jsonchange" @json-change = "jsonchange"  v-model="ruleForm['bodyData']"/>
          <p v-if="isDisable" style="color: red;">格式有误</p>
        </el-form-item>
      </el-form>
      <div v-if="!disFlag" style="text-align: center;">
        <el-button type="primary" :disabled="isDisable" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="resetForm('return')">返回</el-button>
      </div>
      <el-dialog
        width="40%"
        title="Cron表达式"
        :visible.sync="innerVisible"
        append-to-body>
        <crontag @fill="getValue" @hide="getValue('false')"></crontag>
      </el-dialog>
    </el-dialog>

    <!-- 测试 -->
    <el-dialog :close-on-click-modal="false" width="50%" :visible.sync="testdialogTableVisible">
      <div>
        <div>
          <el-form v-if="testdialogTableVisible" ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="80px" class="demo-ruleForm autoClass2">
            <el-form-item label="请求类型" prop="method" style="width:25%;">
              <el-select v-model="ruleForm2['method']">
                <el-option value="GET" label="GET"></el-option>
                <el-option value="POST" label="POST"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="0" prop="url" style="position: relative;width: 65%;">
              <el-input v-model="ruleForm2['url']" @change="changeUrl" :disabled="disFlag" clearable placeholder="请输入请求地址" />
              <div style="position:absolute;top:27px;font-size:10px;color:rgb(255, 30, 30);">格式说明：“http://”  + “ip:” + 端口”  + “接口地址”</div>
            </el-form-item>
            <el-form-item label="" prop="" label-width="0" style="width: 10%;">
              <div style="text-align: center;">
                <el-button @click="closetestdialogTableVisible" size="mini" style="width: 100%;padding: 9px 0;" type="primary">发送</el-button>
              </div>
            </el-form-item>
            <el-form-item label="body参数" prop="body" style="margin-top:6px;width: 100%;min-height: 80px;">
              <vueJsonEditor :disabled="disFlag"  @has-error="jsonchange" @json-change = "jsonchange" v-model="ruleForm2['body']" />
              <p v-if="isDisable" style="color: red;">格式有误</p>
            </el-form-item>
           
          </el-form>
        </div>
        <div class="vueJsonEditor">
          <div v-if="isShowJson">
            <json-view :data="codeInfo"/>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { httpRequestpage, httpRequestsave, httpRequestdelete,apiInfosend,dataModeldatagetList,
  httpRequeststart,httpRequeststop,httpRequesttrigger,dispatchpage,httpRequestupdate
} from '@/api/zt/index'
import experiment from '@/mixins/experiment'
import vueJsonEditor from 'vue-json-editor'
import crontag from '@/views/components/vue-cron-master/Crontab/index.vue'
import {validURL} from '@/utils/validate'
import jsonView from 'vue-json-views'
export default {
  components: {vueJsonEditor,crontag,jsonView},
  mixins: [experiment],
  data() {
    return {
      isShowJson:false,
      bodyParm:null,
      moduleListOptions:[],
      jsonData:{name:'dog',age:2,hobby:{eat:{food:'狗粮',water:'冰可乐'},sleep:{time:'白日梦'}}},
      cronList:[],
      innerVisible:false,
      innerBodyParm:false,
      codeInfo:{},
      width:"50%",
      ruleForm2:{
        url:"",
        method:"GET",
        body:{}
      },
      testdialogTableVisible:false,
      btnIsShow: {
        operate: true,
        update:true,
        startAndEnd:true,
        detile: false,
        del: true
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      title: '新增',
      rules: {
        joinName: [
            { required: true, message: '请输入接入名称', trigger: 'change' }
        ],
        apiAddress: [
            { required: true, message: '请输入API接口地址', trigger: 'change' }
        ],
        bodyData:[
          { required: true, message: '请输入Body参数', trigger: 'change' }
        ],
        requestType: [
            { required: true, message: '请选择请求类型', trigger: 'change' }
        ],
        structure: [
            { required: true, message: '请输入指定结构', trigger: 'change' }
        ],
        tableName: [
            { required: true, message: '请输入表名', trigger: 'change' }
        ]
      },
      rules2:{
        url: [
            { required: true, message: ' ', trigger: 'change' }
        ]
      },
      dialogTableVisible: false,
      ruleForm: {
        "apiAddress": "",
        "appId": "",
        "appKey": "",
        "bodyData": {},
        "createTime": "",
        "cron": "",
        "id": 0,
        "joinName": "",
        "modelId": 0,
        "modelName": "",
        "pageIndex": 0,
        "pageSize": 0,
        "requestType": "",
        "spare1": "",
        "spare2": "",
        "structure": "",
        "tableName": "",
        "updateTime": ""
      },
      userId: '',
      formInline: {
        'dataModelName': ''
      },
      tableUserData: [],
      tabUserList: [
      {
          key: 'joinName',
          title: '接入任务名称'
        },
        {
          key: 'apiAddress',
          title: 'API地址'
        },
        {
          key: 'requestType',
          title: '请求类型'
        },
        {
          key: 'appKey',
          title: 'appKey'
        },
        {
          key: 'bodyData',
          title: 'body参数'
        },
        {
          key: 'structure',
          title: '指定结构'
        },
        {
          key: 'tableName',
          title: '保存的表名'
        }
      ],
      total: 0,
      size: 10,
      page: 1
    }
  },
  created() {
    dispatchpage({
        'pageIndex':1,
        'pageSize':2000,
        'or_orderby_createTime':'dsc',
        'sk_like_dispatchName': ''
      }).then(res => {
        this.cronList = res.data.records
      })
  },
  mounted() {
    dataModeldatagetList({
        'pageIndex': 1,
        'dataModelName':'',
        'dataModelTypeId': '',
        'pageSize': 11111
      }).then(res => {
        this.moduleListOptions = res.data.records
      })
    this.$nextTick(() => {
      this.getUserList()
    })
  },
  methods: {
    changeUrl(){
      if(!this.ruleForm2['url']){
        this.codeInfo = {}
        this.isShowJson = false
      }
    },
    getFocus(){
      this.innerBodyParm = true
    },
    setdataModelTypeName(v){
      this.moduleListOptions.forEach((item,index)=>{
        if(item.id == v){
          this.ruleForm['modelName'] = item.dataModelTypeName
        }
      })
    },
    executeFun(v,type){
      if(type=='start'){
        httpRequeststart({jobId:v}).then(res=>{
          if (res.code == 200) {
            this.getUserList()
            this.$message.success('已启动')
          } else {
            this.errorDialog(res.msg)
          }
        })
      }else if(type=='stop'){
        httpRequeststop({jobId:v}).then(res=>{
          if (res.code == 200) {
            this.getUserList()
            this.$message.success('已停止')
          } else {
            this.errorDialog(res.msg)
          }
        })
      }else if(type=='onec'){
        httpRequesttrigger({jobId:v}).then(res=>{
          if (res.code == 200) {
            this.getUserList()
            this.$message.success('执行成功！')
          } else {
            this.errorDialog(res.msg)
          }
        })
      }
    },
    closetestdialogTableVisible(v){
      if(this.ruleForm2['url'].length==0){
        this.$message.error('请先填写请求地址')
        return 
      }else{
        if(!validURL(this.ruleForm2['url'])){
          this.$message.error('地址输入有误')
          return 
        }
      }
      if(v!='return'){
        apiInfosend(this.ruleForm2).then(res=>{
          try {
            this.codeInfo = JSON.parse(res.msg)
          } catch (error) {
            this.codeInfo = {}
          }
          this.isShowJson = true
        })
        return
      }
    },
    resetRuleForm2(){

    },
    testFun(){
      this.codeInfo = {}
      this.ruleForm2={
        url:"",
        method:"GET",
        body:{}
      }
      this.testdialogTableVisible = true
    },
    deleteSelectData(v) {
      httpRequestdelete([v.id]).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleNodeClick(data) { },
    updataList(){
      let p = JSON.parse(JSON.stringify(this.ruleForm))
      p['bodyData'] = JSON.stringify(p['bodyData'])
      httpRequestupdate(p).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    commitFromData() {
      if(this.ruleForm.requestType=='GET'){
        this.ruleForm['bodyData'] = ''
      }
      if(this.title!='新增'){
        this.updataList()
        return 
      }
      httpRequestsave(this.ruleForm).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleSizeChange(v) {
      this.page = 1
      this.size = v
      this.getUserList()
    },
    handleCurrentChange(v) {
      this.page = v
      this.getUserList()
    },

    // 获取用户列表
    getUserList() {
      this.dialogTableVisible = false
      this.$refs.httbRef.isShowLoading(true)

      httpRequestpage({
        'pageIndex': this.page,
        'pageSize': this.size,
        'or_orderby_createTime':'dsc',
        'sk_like_joinName': this.formInline.dataModelName
      }).then(res => {
        this.tableUserData = res.data.records
        this.total = res.data.total
        this.$refs.httbRef.isShowLoading(false)

      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/assets/styles/auto.scss";
  >>>.json-view-container {
    // background-color: #1e1e1e !important;
}
  .vueJsonEditor{
    border-radius: 4px;
    overflow:scroll;
    max-height:320px;
    border:1px solid #dcdfe6;
    margin-left: 80px;
    max-height: 200px;
    min-height: 150px;
    pointer-events: none;
  }
.addPs{
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
  >div{
    width:50%
  }
  span{
    display: inline-block;
    width: 10%;
  }
}
.autoClass{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .el-form-item{
    width:50%;
  }
}
.autoClass2{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .el-form-item{
    width:50%;
  }
}
.addcs{
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
}
.addcs2 .el-select {
  display: inline-block;
  width: 240px;
}
.autoInput{
  display: inline-block;
  width: 70%;
}
.infoTitle{
  border-bottom:1px solid #e5e5e5;
  margin-bottom: 30px;
  position: relative;
}
.infoTitle>span{
  position: absolute;
  left: 20px;
  background: #fff;
  width:80px;
  top:-15px;
  height:30px;
  text-align: center;
  line-height: 30px;
}
  .el-select{
      width:100%;
  }
  .timing{
    background:#fff;
    padding:20px;
  }
</style>
